package com.girl.controller;

import com.girl.aspect.HttpAspect;
import com.girl.domain.Girl;
import com.girl.domain.Result;
import com.girl.repository.GirlRepository;
import com.girl.service.GirlService;
import com.girl.units.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by zzy on 2017/12/10.
 */
@RestController
public class GirlController {

    @Autowired
    private GirlRepository girlRepository;

    @Autowired
    private GirlService girlService;

    private final  static Logger logger= LoggerFactory.getLogger(HttpAspect.class);

    /**
     * 查询所有女生列表
     * @return
     */
    @GetMapping(value = "/girls")
    public List<Girl> girlList(){
        return girlRepository.findAll();

    }

    /**
     * 新增girl
     * @return
     */
    @PostMapping(value = "/girls")
    public Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult){
        Result result=new Result();
        if(bindingResult.hasErrors()){
            logger.error(bindingResult.getFieldError().getDefaultMessage());
            return ResultUtil.error(1,bindingResult.getFieldError().getDefaultMessage());
        }
        Girl theGirl= girlRepository.save(girl);

        return ResultUtil.success(theGirl);
    }

    /**
     * 查询一个girl
     * @param id
     * @return
     */
    @GetMapping(value = "/girls/{id}")
    public Girl girlFindOne(@PathVariable("id") Integer id){


        return girlRepository.findOne(id);
    }

    /**
     * 修改girl
     * @param cupSize
     * @param age
     * @param id
     * @return
     */
    @PostMapping(value = "/girls/{id}")
    public Girl girlUpdate(@RequestParam("cupSize") String cupSize,
                     @RequestParam("age") Integer age,
                     @PathVariable("id") Integer id){

        Girl girl=new Girl();
        girl.setCupSize(cupSize);
        girl.setAge(age);
        girl.setId(id);
        return girlRepository.save(girl);
    }

    /**
     * 删除girl
     * @param id
     */
    @DeleteMapping(value = "/girls/{id}")
    public void girlDelete(@PathVariable("id") Integer id){
       girlRepository.delete(id);
    }

    /**
     * 根据年龄查询
     * @param age
     * @return
     */
    @GetMapping(value = "/girls/age/{age}")
    public  List<Girl> girlListByAge(@PathVariable("age") Integer age){
        return girlRepository.findByAge(age);
    }

   @GetMapping(value = "/girls/two")
    public  void saveGirlsTow(){
        girlService.insertTwo();
   }


   @GetMapping(value = "/girls/getAge/{id}")
    public void getAge(@PathVariable("id") Integer id) throws Exception {
        girlService.getAge(id);
   }
}
